<template>
  <div class="SalesRecords">
    <div class="SalesRecords-header">
      <div class="SalesRecords-header-search">
        <div class="SalesRecords-header-search-item">
          <div class="SalesRecords-header-search-item-label">编号</div>
          <el-input v-model="searchForm.orderNo" class="SalesRecords-header-search-item-input"
                    placeholder="请输入销售单编号" clearable/>
        </div>
        <div class="SalesRecords-header-search-item">
          <div class="SalesRecords-header-search-item-label">客户</div>
          <el-input v-model="searchForm.customerName" class="SalesRecords-header-search-item-input"
                    placeholder="请输入客户名" clearable/>
        </div>
        <div class="SalesRecords-header-search-item">
          <div class="SalesRecords-header-search-item-label">日期范围</div>
          <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至"
                          start-placeholder="开始日期" end-placeholder="结束日期" unlink-panels
                          :shortcuts="dateShortcuts"
                          class="SalesRecords-header-search-item-input"/>
        </div>
      </div>
      <div class="SalesRecords-header-btn">
        <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
    </div>

    <div class="SalesRecords-table">
      <el-table :data="tableData.list" v-loading="loading" class="SalesRecords-table-main" border stripe>
        <el-table-column type="index" :index="computeIndex" label="序号" width="80" align="center"/>
        <el-table-column prop="orderNo" label="编号" width="140" align="center"/>
        <el-table-column prop="customerName" label="客户" min-width="160" align="center"/>
        <el-table-column prop="orderDate" label="日期" width="140" align="center"/>
        <el-table-column prop="totalAmount" label="合计金额(¥)" width="140" align="center">
          <template #default="{row}">{{ formatMoney(row.totalAmount) }}</template>
        </el-table-column>
        <el-table-column prop="userName" label="最后操作用户" width="140" align="center"/>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{row}">
            <el-button type="info" size="small" @click="handleDetail(row)">详情</el-button>
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" :disabled="!row.canRed" @click="handleRed(row)">红冲</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="SalesRecords-pagination">
      <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10,20,50,100]"
          :total="tableData.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="SalesRecords-pagination-main"
      />
    </div>

    <SalesOrderDetailDialog v-model:visible="detailVisible" :order-id="currentId"/>
    <SalesOrderEditDialog v-model:visible="editVisible" :order-id="currentId" @success="handleEditSuccess"/>
  </div>
</template>
<script setup>
import {ref, onMounted} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {listSalesOrders} from '../../../../api/salesOrderApi.js'
import {redSalesOrder} from "../../../../api/salesOrderApi.js";
import SalesOrderDetailDialog from './SalesOrderDetailDialog.vue'
import SalesOrderEditDialog from './SalesOrderEditDialog.vue'

// 加载状态
const loading = ref(false)

// 搜索表单
const searchForm = ref({orderNo: '', customerName: '', dateRange: []})

// 日期快捷选项
const dateShortcuts = [
  { text: '最近7天', value: () => { const end = new Date(); const start = new Date(); start.setDate(start.getDate()-6); return [start, end] } },
  { text: '本月', value: () => { const d = new Date(); const start = new Date(d.getFullYear(), d.getMonth(), 1); const end = new Date(d.getFullYear(), d.getMonth()+1, 0); return [start, end] } }
]

// 获取本月范围
const getThisMonthRange = () => { const d = new Date(); return [new Date(d.getFullYear(), d.getMonth(), 1), new Date(d.getFullYear(), d.getMonth()+1, 0)] }

// 分页
const pagination = ref({pageNum: 1, pageSize: 10})

// 表格数据
const tableData = ref({ list: [], total: 0 })

// 日期格式化 yyyy-MM-dd
const formatDate = (date) => {
  if (!date) return ''
  const y = date.getFullYear(); const m = String(date.getMonth()+1).padStart(2,'0'); const d = String(date.getDate()).padStart(2,'0')
  return `${y}-${m}-${d}`
}

// 加载数据（API）
const loadData = async () => {
  loading.value = true
  try {
    const condition = {
      orderNo: searchForm.value.orderNo?.trim() || undefined,
      customerName: searchForm.value.customerName?.trim() || undefined
    }
    if (Array.isArray(searchForm.value.dateRange) && searchForm.value.dateRange.length === 2 && searchForm.value.dateRange[0] && searchForm.value.dateRange[1]) {
      condition.dateRange = [formatDate(new Date(searchForm.value.dateRange[0])), formatDate(new Date(searchForm.value.dateRange[1]))]
    }
    const params = { pageNum: pagination.value.pageNum, pageSize: pagination.value.pageSize, condition }
    const res = await listSalesOrders(params)
    tableData.value = { list: res.list || [], total: res.total || 0 }
  } catch (e) {
    console.error('获取销售记录失败:', e)
  } finally { loading.value = false }
}

// 事件
const handleSearch = () => { pagination.value.pageNum = 1; loadData() }
const handleReset = () => { searchForm.value = {orderNo: '', customerName: '', dateRange: getThisMonthRange()}; pagination.value.pageNum = 1; loadData() }
const handleSizeChange = (val) => { pagination.value.pageSize = val; pagination.value.pageNum = 1; loadData() }
const handleCurrentChange = (val) => { pagination.value.pageNum = val; loadData() }

// 弹窗
const detailVisible = ref(false)
const editVisible = ref(false)
const currentId = ref(null)
const handleDetail = (row) => { currentId.value = row.id; detailVisible.value = true }
const handleEdit = (row) => { currentId.value = row.id; editVisible.value = true }
const handleEditSuccess = () => { ElMessage.success('销售单修改成功'); loadData() }
// 新增：红冲占位
const handleRed = (row) => {
  if(!row || !row.canRed) return
  ElMessageBox.confirm(
    `确认红冲销售单 [${row.orderNo}] ?`,
    '确认红冲', { type: 'warning' }
  ).then(async () => {
    await redSalesOrder(row.id).then(() => {
      ElMessage.success('销售单红冲成功')
      loadData()
    })
  }).catch(() => {})
}

// 金额格式化
const formatMoney = (v) => Number(v || 0).toFixed(2)

// 跨页连续序号
const computeIndex = (i) => (pagination.value.pageNum - 1) * pagination.value.pageSize + i + 1

onMounted(() => { searchForm.value.dateRange = getThisMonthRange(); loadData() })
</script>
<style scoped lang="scss">
.SalesRecords {
  display: flex;
  flex-direction: column;
  height: 100%;

  &-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    padding: 20px 0;
    border-bottom: 1px solid #eee;

    &-search {
      display: flex;
      flex: 1;
      flex-wrap: wrap;
      gap: 16px;

      &-item {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 8px;

        &-label {
          font-size: 14px;
          font-weight: 500;
          color: #333;
          width: 80px;
          white-space: nowrap;
        }

        &-input {
          width: 200px;
        }
      }
    }

    &-btn {
      display: flex;
      align-items: center;
      width: 200px;
      flex: 0 0 200px;
      justify-content: flex-end;
      gap: 8px;
    }
  }

  &-table {
    flex: 1;
    padding: 16px 0;

    &-main {
      width: 100%;
    }
  }

  &-pagination {
    display: flex;
    justify-content: center;
    padding: 16px 0;
    border-top: 1px solid #eee;

    &-main {
      .el-pagination {
        justify-content: center;
      }
    }
  }
}
</style>
